package com.fanshuai.queue.priority;

import com.fanshuai.queue.Queue;

/**
 * 优先队列，基于链表实现
 * @param <E>
 */
public class PriorityQueue<E extends Comparable<E>> implements Queue<E> {
    public static class Node<E> {
        public E data;
        public Node<E> pre;
        public Node<E> next;

        public Node() {
            this.data = null;
            this.pre = null;
            this.next = null;
        }

        public Node(E data) {
            this.data = data;
            this.pre = null;
            this.next = null;
        }
    }

    private Node<E> head;
    private Node<E> tail;
    private int size;

    public PriorityQueue() {
        Node<E> node = new Node<>();
        head = node;
        tail = node;
        size = 0;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean isFull() {
        return false;
    }

    @Override
    public void enqueue(E data) {
        Node<E> node = new Node<>(data);

        Node<E> cur = tail;
        while (cur != head) {
            if (data.compareTo(cur.data) > 0) {
                cur = cur.pre;
            } else {
                break;
            }
        }
        Node<E> next = cur.next;

        node.next = next;
        if (next != null) {
            next.pre = node;
        }
        node.pre = cur;
        cur.next = node;

        if (tail == cur) {
            tail = node;
        }

        size++;
    }

    @Override
    public E dequeue() {
        if (size == 0) {
            return null;
        }

        Node<E> node = head.next;
        E data = node.data;

        head.next = node.next;
        if (node.next != null) {
            node.next.pre = head;
        }
        if (node.next == null) {
            tail = node.pre;
        }

        node.pre = null;
        node.next = null;
        node.data = null;

        size--;

        return data;
    }

    @Override
    public E peek() {
        if (size == 0) {
            return null;
        }

        return tail.data;
    }
}
